<?php
require_once('Apps/CapsuleChecker/Model.php');
require_once 'Helper/Helper.php';
class CapsuleChecker {
	
	var $model;
	var $helper;

	
    function __construct()
    {
        $this->model = new mCapsuleChecker();
		$this->helper = new Helper;
    }
    /*
	function register () {
		$user = $_POST['nickname'];
        $pass = md5($_POST['password']);
        $email = $_POST['email'];
		if ( $user == "" )
		{
			echo "no nickname";
			return false;
		} else if ( $pass == "" ){
			echo "no pass";
			return false;
		} else if ( $email == "" ){
			echo "no email";
			return false;
		}
        $acc = array(
            acc_user => $user,
            acc_pass => $pass,
            acc_email => $email,
            acc_type => "normal",
            acc_lang => 'th'
        );
        $a = $this->model->register($acc);  
		if ( $a['success'] == 2 ) {
			echo "2"; 
		} else if  ( $a['success'] == 1 ) {
			echo "1"; 
		}
	}
	*/
	function genToken( $len = 32, $md5 = true ) {
	 
	    # Seed random number generator
	    # Only needed for PHP versions prior to 4.2
	    mt_srand( (double)microtime()*1000000 );
	 
	    # Array of characters, adjust as desired
	    $chars = array(
	        'Q', '@', '8', 'y', '%', '^', '5', 'Z', '(', 'G', '_', 'O', '`',
	        'S', '-', 'N', '<', 'D', '{', '}', '[', ']', 'h', ';', 'W', '.',
	        '/', '|', ':', '1', 'E', 'L', '4', '&', '6', '7', '#', '9', 'a',
	        'A', 'b', 'B', '~', 'C', 'd', '>', 'e', '2', 'f', 'P', 'g', ')',
	        '?', 'H', 'i', 'X', 'U', 'J', 'k', 'r', 'l', '3', 't', 'M', 'n',
	        '=', 'o', '+', 'p', 'F', 'q', '!', 'K', 'R', 's', 'c', 'm', 'T',
	        'v', 'j', 'u', 'V', 'w', ',', 'x', 'I', '$', 'Y', 'z', '*'
	    );
	 
	    # Array indice friendly number of chars; empty token string
	    $numChars = count($chars) - 1; $token = '';
	 
	    # Create random token at the specified length
	    for ( $i=0; $i<$len; $i++ )
	        $token .= $chars[ mt_rand(0, $numChars) ];
	 
	    # Should token be run through md5?
	    if ( $md5 ) {
	 
	        # Number of 32 char chunks
	        $chunks = ceil( strlen($token) / 32 ); $md5token = '';
	 
	        # Run each chunk through md5
	        for ( $i=1; $i<=$chunks; $i++ )
	            $md5token .= md5( substr($token, $i * 32 - 32, 32) );
	 
	        # Trim the token
	        $token = substr($md5token, 0, $len);
	 
	    } return $token;
	}


	
	function reg (){
		header('Content-Type: text/xml; charset=utf-8');
		date_default_timezone_set('UTC');
		$date_now = date('Y-m-');
		$d = date('d')+1;
		$time_now = date('h:i:s');
		$date = $date_now.$d.'T'.$time_now.'Z';
		$acc_token = $this->genToken();
		$date_sql = $this->helper->slashOperation($date_now.$d." ".$time_now);
		$nick = $_POST['nick'];
		$email = $_POST['email'];
		$pass = md5($_POST['pass']);
		$lang = $_POST['lang'];
		$udid = $_POST['udid'];
		$result = $this->model->reg($nick,$email,$pass,$lang,$udid,$date_sql,$acc_token);
		if ( $result['success'] == 1 ) {
			/*
			echo <<<HTML
			<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
			<plist version="1.0">
			<dict>
				<key>nick</key>
				<string></string>
				<key>errCode</key>
				<string>1</string>
				<key>errMsg</key>
				<string>This email is already in use.</string>
				<key>token</key>
				<string></string>
				<key>uid</key>
				<string></string>
				<key>exp</key>
				<date></date>
				<key>comm</key>
				<string>reg</string>
			</dict>
			</plist>
HTML;*/
			$arr = array('nick' => " ", 'errCode' => 1, 'errMsg' => "This email is already in use.", 'token' => " ", 'uid' => " " , 'exp' => " " , 'comm' => "reg" );
			echo json_encode($arr);
	} else if ( $result['success'] == 0 ) {
		/*
		echo <<<HTML
			<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
			<plist version="1.0">
			<dict>
				<key>nick</key>
				<string>{$nick}</string>
				<key>errCode</key>
				<string>0</string>
				<key>errMsg</key>
				<string>register success.</string>
				<key>token</key>
				<string>{$acc_token}</string>
				<key>uid</key>
				<string>{$result['acc_id']}</string>
				<key>exp</key>
				<date>{$date}</date>
				<key>comm</key>
				<string>reg</string>
			</dict>
			</plist>
HTML; */
			$arr = array('nick' => "{$nick}", 'errCode' => 0, 'errMsg' => "register success.", 'token' => "{$acc_token}", 'uid' => "{$result['acc_id']}" , 'exp' => "{$date}" , 'comm' => "reg" );
			echo json_encode($arr);
		}
	}
	function login() {
		header('Content-Type: text/xml; charset=utf-8');
		date_default_timezone_set('UTC');
		$date_now = date('Y-m-');
		$d = date('d')+1;
		$time_now = date('h:i:s');
		$date = $date_now.$d.'T'.$time_now.'Z';
		$email = $_POST['email'];
		$pass = md5($_POST['pass']);
		$lang = $_POST['lang'];
		$UDID = $_POST['UDID'];
		$acc_token = $this->genToken();
		$date_sql = $this->helper->slashOperation($date_now.$d." ".$time_now);
		$result = $this->model->login($email,$pass,$lang,$UDID,$acc_token,$date_sql);
		// print_r($result);
		if ( $result['success'] == 0 ) {
			/*
			echo <<<HTML
			<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
			<plist version="1.0">
			<dict>
				<key>nick</key>
				<string></string>
				<key>errCode</key>
				<string>1</string>
				<key>errMsg</key>
				<string>This email address is not found.</string>
				<key>token</key>
				<string></string>
				<key>uid</key>
				<string></string>
				<key>exp</key>
				<date></date>
				<key>comm</key>
				<string>login</string>
			</dict>
			</plist>
HTML;*/
			$arr = array('nick' => " ", 'errCode' => 1, 'errMsg' => "This email address is not found.", 'token' => " ", 'uid' => " " , 'exp' => " " , 'comm' => "login" );
			echo json_encode($arr);
		} else if ( $result['success'] == 1 ) {
			/*
			echo <<<HTML
			<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
			<plist version="1.0">
			<dict>
				<key>nick</key>
				<string></string>
				<key>errCode</key>
				<string>2</string>
				<key>errMsg</key>
				<string>The password is incorrect.</string>
				<key>token</key>
				<string></string>
				<key>uid</key>
				<string></string>
				<key>exp</key>
				<date></date>
				<key>comm</key>
				<string>login</string>
			</dict>
			</plist>
HTML;*/
			$arr = array('nick' => " ", 'errCode' => 1, 'errMsg' => "This email address is not found.", 'token' => " ", 'uid' => " " , 'exp' => " " , 'comm' => "login" );
			echo json_encode($arr);
		} else if  ( $result['success'] == 2 ) {
			/*echo <<<HTML
			<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
			<plist version="1.0">
			<dict>
				<key>nick</key>
				<string>{$result['acc_user']}</string>
				<key>errCode</key>
				<string>0</string>
				<key>errMsg</key>
				<string>login success.</string>
				<key>token</key>
				<string>{$result['acc_token']}</string>
				<key>uid</key>
				<string>{$result['acc_id']}</string>
				<key>exp</key>
				<date>$date</date>
				<key>comm</key>
				<string>login</string>
			</dict>
			</plist>
HTML;*/
			$arr = array('nick' => "{$result['acc_user']}", 'errCode' => 0, 'errMsg' => "login success.", 'token' => "{$result['acc_token']}", 'uid' => "{$result['acc_id']}" , 'exp' => "{$date}" , 'comm' => "login" );
			echo json_encode($arr);
		}
	}
	
	function fblogin (){
		header('Content-Type: text/xml; charset=utf-8');
		$fbToken = $_GET['fbToken'];
		$fbExp = $_POST['fbExp'];
		$lang = $_POST['lang'];
		$UDID = $_POST['UDID'];
		$acc_token = $this->genToken();
		date_default_timezone_set('UTC');
		$date_now = date('Y-m-');
		$d = date('d')+1;
		$time_now = date('h:i:s');
		$date = $date_now.$d.'T'.$time_now.'Z';
		// https://graph.facebook.com/me?access_token=$fbToken
	   //retrieves the users facebook_id
	   $url = 'https://graph.facebook.com/me/?access_token='.$fbToken;
	   $curl_handle=curl_init();
	   curl_setopt($curl_handle,CURLOPT_URL,$url);
	   curl_setopt($curl_handle,CURLOPT_CONNECTTIMEOUT,2);
	   curl_setopt($curl_handle,CURLOPT_RETURNTRANSFER,1);
	   $buffer = curl_exec($curl_handle);
	   curl_close($curl_handle);
	   $jobj = json_decode($buffer);
	   $facebook_nick = $jobj->name;
	   $facebook_email = $jobj->email;
	   $date_sql = $this->helper->slashOperation($date_now.$d." ".$time_now);
	   $result = $this->model->fblogin($facebook_email,$facebook_nick,$date_sql,$acc_token);
	   /*
	   echo "<pre>";
	   print_r($jobj);
	   echo "</pre>";
	   */
		echo <<<HTML
		<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
			<plist version="1.0">
			<dict>
				<key>nick</key>
				<string>{$facebook_nick}</string>
				<key>errCode</key>
				<string>0</string>
				<key>errMsg</key>
				<string>fb reg success.</string>
				<key>token</key>
				<string>{$acc_token}</string>
				<key>uid</key>
				<string>{$result['acc_id']}</string>
				<key>exp</key>
				<date>$date</date>
				<key>comm</key>
				<string>fblogin</string>
				<key>alreadyReg</key>
				<true/>
				<key>email</key>
				<string>{$facebook_email}</string>
			</dict>
			</plist>
HTML;
	}
	
	function tklogin (){
		header('Content-Type: text/xml; charset=utf-8');
		date_default_timezone_set('UTC');
		$date_now = date('Y-m-');
		$d = date('d')+1;
		$time_now = date('h:i:s');
		$token = $_POST['token'];
		$lang = $_POST['lang'];
		$UDID = $_POST['UDID'];
		if ( $token == "" || $lang == "" || $UDID == "" )
		{
			return false;
		}
		$acc_token = $this->genToken();
		$date = $date_now.$d.'T'.$time_now.'Z';
		$date_sql = $this->helper->slashOperation($date_now.$d." ".$time_now);
		$result = $this->model->tklogin($token,$lang,$UDID,$acc_token,$date_sql);
		if (  $result['success'] == 0 ) {
			/*
			echo <<<HTML
			<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
			<plist version="1.0">
			<dict>
				<key>nick</key>
				<string> {$result['acc_user']} </string>
				<key>errCode</key>
				<string>0</string>
				<key>errMsg</key>
				<string>token exp success.</string>
				<key>token</key>
				<string>{$result['acc_token']}</string>
				<key>uid</key>
				<string>{$result['acc_id']}</string>
				<key>exp</key>
				<date>$date</date>
				<key>comm</key>
				<string>tklogin</string>
			</dict>
			</plist>
HTML;*/
			$arr = array('nick' => "{$result['acc_user']}", 'errCode' => 0, 'errMsg' => "token exp success.", 'token' => "{$result['acc_token']}", 'uid' => "{$result['acc_id']}" , 'exp' => "{$date}" , 'comm' => "tklogin" );
			echo json_encode($arr);
		} else if (  $result['success'] == 1 ) {
			/*echo <<<HTML
			<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
			<plist version="1.0">
			<dict>
				<key>nick</key>
				<string> </string>
				<key>errCode</key>
				<string>1</string>
				<key>errMsg</key>
				<string>This is no token.</string>
				<key>token</key>
				<string> </string>
				<key>uid</key>
				<string> </string>
				<key>exp</key>
				<date> </date>
				<key>comm</key>
				<string>tklogin</string>
			</dict>
			</plist>
HTML;*/
			$arr = array('nick' => " ", 'errCode' => 1, 'errMsg' => "This is no token.", 'token' => " ", 'uid' => " " , 'exp' => " " , 'comm' => "tklogin" );
			echo json_encode($arr);
		}
	}
	
	function logout(){
		header('Content-Type: text/xml; charset=utf-8');
		$token = $_POST['token'];
		$result = $this->model->logout($token);
		if (  $result['success'] == 0 ) {
			/*echo <<<HTML
			<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
			<plist version="1.0">
			<dict>
				<key>token</key>
				<string> </string>
				<key>errCode</key>
				<string>0</string>
				<key>errMsg</key>
				<string>logout success.</string>
				<key>comm</key>
				<string>logout</string>
			</dict>
			</plist>
HTML;*/
			$arr = array('token' => " ", 'errCode' => 0, 'errMsg' => "logout success.", 'comm' => "logout" );
			echo json_encode($arr);
		} else if (  $result['success'] == 1 ) {
		/*	echo <<<HTML
			<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
			<plist version="1.0">
			<dict>
				<key>token</key>
				<string> </string>
				<key>errCode</key>
				<string>1</string>
				<key>errMsg</key>
				<string>This is no token.</string>
				<key>comm</key>
				<string>logout</string>
			</dict>
			</plist>
HTML;*/
			$arr = array('token' => " ", 'errCode' => 1, 'errMsg' => "This is no token.", 'comm' => "logout" );
			echo json_encode($arr);
		}
	}
}






